import os
import re

# 定义要遍历的目录路径（Windows路径使用原始字符串或双反斜杠）
directory = r'D:\software\datax.tar\datax\bin'  # 使用原始字符串(r前缀)或双反斜杠

# 定义替换规则
replacements = {
    '/animation_universe_313_test?': '/animation_universe_313?',
    '/ac_cloud_resource_pre?': '/ac_cloud_resource_prod?',
    '"username": "xyz_pre_prod",': '"username": "xyz_universe",',
    '"username": "rrdm_ms_pre",': '"username": "rrdm_ms_prod",',
    '"password": "jCswzehj8Hw5P8D3",': '"password": "LpXiy$MSOzAHmn$1x",',
    '"password": "pZhKCGZY9C1RWM1e",': '"password": "9yntSSaF62ceejkb",'
}

def process_file(file_path):
    try:
        # 尝试utf-8编码读取，如果失败则尝试gbk
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
        except UnicodeDecodeError:
            with open(file_path, 'r', encoding='gbk') as f:
                content = f.read()
        
        # 执行所有替换
        for old, new in replacements.items():
            content = content.replace(old, new)
        
        # 构建新文件名（将-pre替换为-prod）
        dir_name = os.path.dirname(file_path)
        file_name = os.path.basename(file_path)
        new_file_name = file_name.replace('-pre', '-prod')
        new_file_path = os.path.join(dir_name, new_file_name)
        
        # 写入新文件（使用utf-8编码）
        with open(new_file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        
        print(f"成功处理: {file_path} -> {new_file_path}")
        return True
    except Exception as e:
        print(f"处理文件 {file_path} 时出错: {str(e)}")
        return False

def main():
    # 检查目录是否存在
    if not os.path.isdir(directory):
        print(f"错误: 目录不存在 - {directory}")
        return
    
    print(f"开始遍历目录: {directory}")
    
    # 遍历目录
    processed_count = 0
    for root, dirs, files in os.walk(directory):
        for file in files:
            # 检查文件名是否包含aigc和rrdm（不区分大小写）
            if 'aigc' in file.lower() or 'rrdm' in file.lower():
                file_path = os.path.join(root, file)
                print(f"找到匹配文件: {file_path}")
                if process_file(file_path):
                    processed_count += 1
    
    print(f"处理完成。共处理了 {processed_count} 个文件。")

if __name__ == '__main__':
    main()